package com.jsj.controller;

import com.jsj.domain.Problem;
import com.jsj.service.ProblemService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.framework.web.domain.server.Sys;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ruoyi.common.utils.PageUtils.startPage;

@RestController
@RequestMapping("/problem")
public class ProblemController {
    private ProblemService problemService;

    @Autowired
    public void setProblemService(ProblemService problemService) {
        this.problemService = problemService;
    }

    /**
     * 教师查询试题
     */
    @RequestMapping(value = "/queryByCreator/{creator}", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('student,teacher,admin')")
    public List<Problem> queryByCreator(@PathVariable("creator") String creator) {
        startPage();
        return problemService.queryByCreator(creator);
    }

    /**
     * 查询试题
     */
    @RequestMapping(value = "/queryById/{id}", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('student,teacher,admin')")
    public Problem queryById(@PathVariable("id") int id) {
        return problemService.queryById(id);
    }

    /**
     * 查询作业试题
     */
    @RequestMapping(value = "/queryByTopic/{topicId}", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('student,teacher,admin')")
    public List<Problem> queryByTopic(@PathVariable("topicId") int topicId) {
        return problemService.queryByTopic(topicId);
    }

    /**
     * 查询作业试题通过单表
     */
    @RequestMapping(value = "/queryByTopicId/{topicId}", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('student,teacher,admin')")
    public List<Problem> queryByTopicId(@PathVariable("topicId") int topicId) {
        List<Problem> list=problemService.queryByTopicId(topicId);
        for(Problem problem:list){
            String str=problem.getTitle();
            Document document= Jsoup.parse(str);
            Element element=document.select("p").first();
            String p=element.text();
            element=document.select("img[src]").first();
            String imgSrc="";
            try {
               imgSrc = element.attr("src");
            }
            catch(Exception e){
            }
            problem.setTitle("<div class=\"TiMu\">" +
                    "<div class=\"Zy_TItle clearfix\">" +
                    "<div class=\"Zy_TItle_p\"><p>"+p+"</p><br/>" +
                    "<cc><p>"+"<img src=\""+imgSrc+"\"  width=\"500px\">" +
                    "</p></cc></div></div></div>");
        }

        return list;
        //return problemService.queryByTopicId(topicId);

    }
//    /**
//     * 学生查询作业试题提交结果
//     */
//    @RequestMapping(value = "/queryByStudent/{topicId}", method = {RequestMethod.POST})
//    @ResponseBody
//    @PreAuthorize("@ss.hasAnyRoles('student,teacher,admin')")
//    public List<Problem> queryByStudent(@PathVariable("topicId") int topicId) {
//        return problemService.queryByTopicId(topicId);
//
//    }
    @RequestMapping(value = "/queryNumber/{id}", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('student,teacher,admin')")
    public Problem queryNumber(@PathVariable("id") int id) {
        return problemService.queryNumber(id);
    }
    /**
     * 创建试题
     */
    @RequestMapping(value = "/insert", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('teacher,admin')")
    public AjaxResult insert(@RequestBody Problem problem) {
        /*if (problemService.insert(problem) == 0) {
            return AjaxResult.error("创建试题失败");
        }*/
        String str=problem.getTitle();
        Document document= Jsoup.parse(str);
        Elements elements=document.select("img[src]");
        if(!elements.isEmpty()) {
            if (elements.size() > 1) {
                return AjaxResult.error("错误数量");
            }
            Element element = elements.get(0);
            String res = element.attr("src");
            String bukUrl = null;
            try {
                bukUrl = uploadfile(res);
            } catch (Exception e) {
                System.out.println(e);
                return AjaxResult.error("创建试题失败");
            }
            System.out.println(bukUrl);
            if (bukUrl == null) {
                return AjaxResult.error("创建试题失败");
            }
            element.attr("src", bukUrl);
            element.attr("style", "width: 50px;height: 50px;");
            str = document.body().html();
            System.out.println(str);
            problem.setTitle(str);
        }
        if (problemService.insert(problem) == 0) {
            return AjaxResult.error("创建试题失败");
        }
        return AjaxResult.success("创建试题成功");
    }

    /**
     * 删除试题
     */
    @RequestMapping(value = "/delete/{id}", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('teacher,admin')")
    public AjaxResult delete(@PathVariable("id") int id) {
        if (problemService.delete(id) == 0) {
            return AjaxResult.error("删除试题失败");
        }
        return AjaxResult.success("删除试题成功");
    }

    /**
     * 修改试题
     */
    @RequestMapping(value = "/update", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('teacher,admin')")
    public AjaxResult update(@RequestBody Problem problem) {
        String str=problem.getTitle();
        Document document= Jsoup.parse(str);
        Elements elements=document.select("img[src]");
        if(!elements.isEmpty()) {
            if (elements.size() > 1) {
                return AjaxResult.error("错误数量");
            }
            Element element = elements.get(0);
            String res = element.attr("src");
            String bukUrl = null;
            try {
                bukUrl = uploadfile(res);
            } catch (Exception e) {
                System.out.println(e);
                return AjaxResult.error("创建试题失败");
            }
            System.out.println(bukUrl);
            if (bukUrl == null) {
                return AjaxResult.error("创建试题失败");
            }
            element.attr("src", bukUrl);
            element.attr("style", "width: 50px;height: 50px;");
            str = document.body().html();
            System.out.println(str);
            problem.setTitle(str);
        }
        if (problemService.update(problem) == 0) {
            return AjaxResult.error("修改试题失败");
        }
        return AjaxResult.success("修改试题成功");
    }

    private String uploadfile(String res) throws InvalidPortException, InvalidEndpointException, IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        //你的endpoint,本机可以不变
        String endpoint = "http://124.222.166.200:9000/";
        //你的accessKey
        String accessKey = "Z311B8GV7BKOILXRW31O";
        //你的sercetKey
        String secretKey = "KkQLVA+p4O9GAgl6cdWeTn+L6JSAd2aQMloStE7s";
        //你的bucket
        String bucketName = "daily";
        // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
        MinioClient minioClient = new MinioClient(endpoint, accessKey, secretKey);

        // 检查存储桶是否已经存在
        boolean isExist = minioClient.bucketExists(bucketName);
        if (!isExist) {
            System.out.println("Bucket not exists.");
            return null;
        }
        String nameSuffix = UUID.randomUUID().toString() + ".jpg";
        try {
            res = res.substring(res.indexOf(",", 1) + 1, res.length());
            byte[] decode = Base64.decode(res);
            InputStream byteArrayInputStream = new ByteArrayInputStream(decode);
            String url = "/show?fileName=" + nameSuffix;
            PutObjectOptions options = new PutObjectOptions(byteArrayInputStream.available(), PutObjectOptions.MIN_MULTIPART_SIZE);
            options.setContentType("image/png");
            minioClient.putObject(bucketName, nameSuffix, byteArrayInputStream, options);
        }
        catch (Exception e){
            System.out.println(e);
            return  null;
        }
        return "http://124.222.166.200:9000/daily/" + nameSuffix;
    }

    @RequestMapping(value = "/queryProblemById/{topicId}", method = {RequestMethod.POST})
    @ResponseBody
    @PreAuthorize("@ss.hasAnyRoles('student,teacher,admin')")
    public List<Problem> queryByProblemId(@PathVariable("topicId") int topicId) {
        List<Problem> list=problemService.queryByTopic(topicId);
        for(Problem problem:list){
            String str=problem.getTitle();
            Document document= Jsoup.parse(str);
            Element element=document.select("p").first();
            String p=element.text();
            element=document.select("img[src]").first();
            String imgSrc=element.attr("src");
            problem.setTitle("<div class=\"TiMu\">" +
                    "<div class=\"Zy_TItle clearfix\">" +
                    "<div class=\"Zy_TItle_p\"><p>"+p+"</p>" +
                    "<cc><p>"+"<img src=\""+imgSrc+"\"  width=\"500px\">" +
                    "</p></cc></div></div></div>");
        }

        return problemService.queryByTopic(topicId);
    }
}
